﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class Police_Question_ProblemNew : System.Web.UI.Page
{
    private string ConstDepartmentID;

    protected void Page_Load(object sender, EventArgs e)
    {
        ConstDepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        if (!IsPostBack)
        {
            Bind();
        }

    }
    private void Bind()
    {
        Question2DataContext db = new Question2DataContext();
        var result = from v in db.SecuritySubject2 where v.CreateDepartment == ConstDepartmentID && !(from o in db.Examination2 select o.SID).Contains(v.Id) orderby v.CreateTime ascending select v;
        foreach (SecuritySubject2 s in result)
        {
            ListItem item = new ListItem();
            item.Text = "".PadRight(2 * int.Parse(s.Flag.ToString()), '　') + s.Caption;
            item.Value=s.Id.ToString();

            dptSubject.Items.Add(item);
        }        

        if (Request["ID"] != null)
            this.dptSubject.SelectedValue = Request["ID"];

        BindAnswerID();
            
    }

    private void BindAnswerID()
    {
        int Start = Convert.ToInt32('A');
        for (int i = Start; i < Start + 26; i++)
        {
            dptAnswer.Items.Add(new ListItem(Convert.ToChar(i).ToString(), Convert.ToChar(i).ToString()));
        }
        
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            lblPrompt.Text = "";
            Question2DataContext db = new Question2DataContext();
            Yipusoft.Account.Model.UserInfo user = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
            if (hidvalue.Value.Trim() == "")
            {
                int IsMultiple = ckbright.Checked ? 1 : 0;
                string RightResult = GetRightResult();

                //添加问题
                Guid PID = Guid.NewGuid();
                db.InsertProblem2(PID, new Guid(dptSubject.SelectedValue), txtProblem.Text.Trim(), user.DepartmentID, DateTime.Now, user.UserID, txtRemark.Text, IsMultiple, RightResult, decimal.Parse(txtGuardCount.Text));
                lblPrompt.Text = "操作已成功";
                SetRightResult(PID);
            }
            else
            {
                string[] strArry = hidvalue.Value.Split(new char[] { '|' });
                foreach (string id in strArry)
                {
                    var obj = from v in db.SecurityProblem2 where v.Id == new Guid(id) && v.Sid == new Guid(dptSubject.SelectedValue) select v;
                    if (obj.Count() <= 0)
                    {
                        var problem = from p in db.SecurityProblem2 where p.Id == new Guid(id) select p;
                        foreach (SecurityProblem2 pa in problem)
                        {
                            Guid ID = Guid.NewGuid();
                            Guid Old = pa.Id;
                            Guid Sid = new Guid(dptSubject.SelectedValue);
                            SecurityProblem2 pm = new SecurityProblem2();
                            pm.Id = ID;
                            pm.Sid = Sid;
                            pm.Title = pa.Title;
                            pm.RightResult = pa.RightResult;
                            pm.Remark = pa.Remark;
                            pm.IsMultiple = pa.IsMultiple;
                            pm.CreateDepartment = pa.CreateDepartment;
                            pm.CreateUser = pa.CreateUser;
                            pm.CreateTime = DateTime.Now;
                            pm.GuardCount = pa.GuardCount.Value;
                            db.SecurityProblem2.InsertOnSubmit(pm);
                            db.SubmitChanges();

                            var op = from o in db.SecurityOption2 where o.PId == Old select o;

                            foreach (SecurityOption2 o in op)
                            {
                                SecurityOption2 pp = new SecurityOption2();
                                pp.Id = Guid.NewGuid();
                                pp.PId = ID;
                                pp.No = o.No;
                                pp.Mark = o.Mark;
                                pp.OptionContent = o.OptionContent;
                                pp.IsRight = o.IsRight;
                                pp.No = o.No;
                                db.SecurityOption2.InsertOnSubmit(pp);
                                db.SubmitChanges();

                                lblPrompt.Text = "操作已成功";
                                
                            }
                            

                        }

                    }
                }
               
            }
            ClearData();
            dptAnswer.Enabled = true;
            BindAnswerID();
        }
        catch (Exception ex)
        {
            lblPrompt.Text = ex.Message.ToString();
        }
        Response.Redirect("ProblemNew.aspx?ID="+Request["ID"]);

    }

    private void ClearData()
    {
        txtMark.Text = "";
        txtProblem.Text = "";
        txtRemark.Text = "";
        txtGuardCount.Text = "";
        txtAnswer.Text = "";
        ViewState["Item"] = null;
        dptAnswer.Items.Clear();
        rbtnMutile.Enabled = true;
        rbtnSingle.Enabled = true;
        lstAnswer.Items.Clear();
        rbtnMutile.Checked = false;
        rbtnSingle.Checked = false;
        btnAddAnswer.Text = "添加答案";

    }
    //添加选择项
    private void SetRightResult(Guid pid)
    {
        Question2DataContext db = new Question2DataContext();
        if (ViewState["Item"] == null)
            return;
        List<MyItem> list = ViewState["Item"] as List<MyItem>;

        for (int i = 0; i < list.Count; i++)
        {

            db.SecurityOption2.InsertOnSubmit(new SecurityOption2() { Id = Guid.NewGuid(), No = list[i].No, OptionContent = list[i].Name, Mark = decimal.Parse(list[i].Mark), PId = pid, IsRight = list[i].IsRight });
            db.SubmitChanges();

        }

    }
    //获取正确答案
    private string GetRightResult()
    {

        if (ViewState["Item"] == null)
            return "";

        List<MyItem> list = ViewState["Item"] as List<MyItem>;
        string ReturnStr = string.Empty;
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].IsRight)
                ReturnStr += i.ToString() + ",";


        }
        return ReturnStr;

    }

    protected void rbtnMutile_CheckedChanged(object sender, EventArgs e)
    {
        rbtnMutile.Enabled = false;
        rbtnSingle.Enabled = false;
        txtAnswer.Enabled = true;
    }

    private void AnswerID()
    { 
          List<MyItem> mylist = ViewState["Item"] as List<MyItem>;
        if(mylist==null)
            return;

        foreach (MyItem itm in mylist)
        {
            dptAnswer.Items.Remove(itm.No);
        }
    }
    protected void btnAddAnswer_Click(object sender, EventArgs e)
    {
        if (btnAddAnswer.CommandArgument.Trim() == "")
        {
            lblPrompt.Text = "";
            if (txtAnswer.Text.Trim() != "")
            {
                foreach (ListItem m in lstAnswer.Items)
                {
                    if (m.Text.Trim().Equals(txtAnswer.Text.Trim()))
                    {
                        lblPrompt.Text = "此答案已存在";
                        BindListBox();
                        return;
                    }
                }

                ListItem item = new ListItem(txtAnswer.Text.Trim());
                List<MyItem> list = new List<MyItem>();
                if (ViewState["Item"] != null)
                    list = ViewState["Item"] as List<MyItem>;
                list.Add(new MyItem() { Name = item.Text, Mark = txtMark.Text.Trim(), IsRight = ckbright.Checked, No=dptAnswer.SelectedValue });

                if (ckbright.Checked)
                {
                    item.Attributes.CssStyle.Add("Color", "red");

                }

                lstAnswer.Items.Add(item);
                ViewState["Item"] = list;

                txtAnswer.Text = "";
                txtMark.Text = "";


            }
            AnswerID();
        }
        else
        {
            List<MyItem> list = ViewState["Item"] as List<MyItem>;

            if (list==null)
                return;

            MyItem pt = list.Where(o => o.Name.Trim() == btnAddAnswer.CommandArgument.Trim()).Single();
            list.Remove(pt);
            MyItem it = new MyItem();
            it.IsRight = ckbright.Checked;
            it.Name = txtAnswer.Text.Trim();
            it.Mark = txtMark.Text.Trim();
            it.No = dptAnswer.SelectedValue;
            list.Insert(0, it);

            ViewState["Item"] = list;
            
            
            
            btnAddAnswer.CommandArgument = "";
            btnAddAnswer.Text = "添加答案";
        }
        BindListBox();


    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        btnAddAnswer.CommandArgument = "";
        btnAddAnswer.Text = "添加答案";
        List<MyItem> mylist = ViewState["Item"] as List<MyItem>;
        foreach (ListItem item in lstAnswer.Items)
        {
            if (item.Selected && mylist.Count > 0)
            {

                mylist.Remove(mylist.Where(o => o.Name == item.Text).Single());

            }
        }
        BindListBox();
    }

    private void BindListBox()
    {
        lstAnswer.Items.Clear();
        if (ViewState["Item"] != null)
        {
            List<MyItem> list = ViewState["Item"] as List<MyItem>;
            foreach (MyItem item in list)
            {
                ListItem tm = new ListItem(item.Name);
                if (item.IsRight)
                {
                    tm.Attributes.CssStyle.Add("Color", "Red");
                }
                lstAnswer.Items.Add(tm);
            }
        }
    }
    protected void lstAnswer_SelectedIndexChanged(object sender, EventArgs e)
    {
        Question2DataContext db = new Question2DataContext();
        List<MyItem> list = null;
        if (ViewState["Item"] != null)
            list = ViewState["Item"] as List<MyItem>;

        BindAnswerID();
        foreach (ListItem item in lstAnswer.Items)
        {

            if (item.Selected)
            {

                
                if (list==null)
                    return;
                MyItem opt = list.Where(o => o.Name.Trim() == item.Text.Trim()).Single();

                txtAnswer.Text = opt.Name;
                ckbright.Checked = opt.IsRight;
                txtMark.Text = opt.Mark.ToString();
                dptAnswer.SelectedValue = opt.No;
                btnAddAnswer.CommandArgument = opt.Name.ToString();
                btnAddAnswer.Text = "修改答案";


            }
        }

        dptAnswer.Enabled = false;
        
    }
    protected void btnparent_Click(object sender, EventArgs e)
    {
        Response.Redirect("QuestionList.aspx");
    }
}

[Serializable]
public class MyItem
{
    public string Name
    {
        set;
        get;
    }

    public string Mark
    {
        set;
        get;
    }

    public bool IsRight
    {
        set;
        get;
    }
    public string No
    {
        set;
        get;
    }
}
